const app = getApp();
Page({
  data: {
    currentTab: 'precollecta',
    SwiperList: [],
    formData: {
      name: '',
      //userId:'',
      //status:'',
      nationality:'',
      formTime:'',
      gender: 1,
      birthDate: '',
      politicalAffiliation: '',
      nativePlace:'',
      idCard: '',
      studentId:'',
      college: '',
      className: '',
      contactNumber: '',
      homeAddress: '',
      imgUrl: '',
      primaryEducation: {
        startDate: '',
        endDate: '',
        schoolName: ''
      },
      juniorEducation: {
        startDate: '',
        endDate: '',
        schoolName: ''
      },
      seniorEducation: {
        startDate: '',
        endDate: '',
        schoolName: ''
      },
      universityEducation: {
        startDate: '',
        endDate: '',
        schoolName: ''
      }
    },
    politicalStatusOptions: ['群众', '共青团员', '中共党员', '其他'],
    isSubmitting: false
  },

  onLoad() {
    // 尝试恢复已保存的表单数据
    const savedData = wx.getStorageSync('precollectFormData');
    if (savedData) {
      this.setData({
        formData: JSON.parse(savedData)
      });
    }
    this.getSwiperList()
  },

  // 处理输入框变化
  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    this.setFormData(field, value);
  },

  // 处理单选框变化
  handleRadioChange(e) {
    const { field } = e.currentTarget.dataset;
    this.setFormData(field, e.detail.value);
    let value = e.detail.value;

    // 如果是性别字段，确保转换为数字
    if (field === 'gender') {
      value = parseInt(value,10); // 将字符串转换为数字
    }
    this.setFormData(field, value);
  },

  // 处理日期选择器变化
  handleDateChange(e) {
    const { field } = e.currentTarget.dataset;
    this.setFormData(field, e.detail.value);
  },

  // 处理选择器变化
  handlePickerChange(e) {
    const { field } = e.currentTarget.dataset;
    const value = this.data.politicalStatusOptions[e.detail.value];
    this.setFormData(field, value);
  },

  // 选择照片
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setFormData('imgUrl', res.tempFilePaths[0]);
      }
    });
  },

  // 更新表单数据并自动保存
  setFormData(field, value) {
    this.setData({
      [`formData.${field}`]: value
    }, () => {
      // 自动保存
      wx.setStorageSync('precollectFormData', JSON.stringify(this.data.formData));
    });
  },

  // 验证表单数据
  validateForm() {
    const { formData } = this.data;
    if (!formData.name) return '请输入姓名';
    if (!formData.birthDate) return '请选择出生日期';
    if (!formData.idCard) return '请输入身份证号';
    if (!formData.contactNumber) return '请输入联系电话';
    if (!formData.homeAddress) return '请输入家庭地址';
    //if (!formData.photo) return '请上传照片';

    // 教育信息验证
    if (!formData.primaryEducation?.startDate || !formData.primaryEducation?.endDate) {
      return '请填写小学的起止时间';
    }
    if (!formData.juniorEducation?.startDate || !formData.juniorEducation?.endDate) {
      return '请填写初中的起止时间';
    }
    if (!formData.seniorEducation?.startDate || !formData.seniorEducation?.endDate) {
      return '请填写高中的起止时间';
    }
    if (!formData.universityEducation?.startDate || !formData.universityEducation?.endDate) {
      return '请填写大学的起止时间';
    }
    return null;
  },

  handleSubmit() {
    if (this.data.isSubmitting) return;

    const error = this.validateForm();
    if (error) {
      wx.showToast({
        title: error,
        icon: 'none'
      });
      return;
    }
    
    // 显示加载中
    wx.showLoading({
      title: '提交中...',
      mask: true
    });
    
    this.setData({ isSubmitting: true });

    wx.request({
      url: `${app.globalData.baseUrl}/api/index/submit`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: this.data.formData,
      success: (res) => {
        if (res.statusCode==200) {
          wx.showToast({
            title: '提交成功',
            icon: 'success'
          });
          wx.removeStorageSync('precollectFormData');
        } else {
          wx.showToast({
            title: res.data.message || '提交失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        // 隐藏加载提示
        wx.hideLoading();
        this.setData({ isSubmitting: false });
      }
    });
  },
  
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab
    });
  },

  // 处理日期选择
  bindDateChange(e) {
    const type = e.currentTarget.dataset.type;
    const field = e.currentTarget.dataset.field;
    const selectedDate = e.detail.value;
    
    // 修改设置数据的方式
    this.setData({
      [`formData.${type}Education.${field}`]: selectedDate
    }, () => {
      // 自动保存
      wx.setStorageSync('precollectFormData', JSON.stringify(this.data.formData));
    });
  },
  getSwiperList(){
    wx.request({
  url: `${app.globalData.baseUrl}/api/index/swiper`,
  method:'GET',
  success:(res)=>{
if(res.statusCode===200){
     this.setData({
       SwiperList : res.data.data
     });
   }else{
     console.error('请求失败，状态码:', res.statusCode);
   }
},
fail:(err) =>{
       console.log('请求失败:', err);
}
})
}
})